package com.yuanheng100.ems4j.service;

import com.alibaba.fastjson.JSON;
import com.yuanheng100.ems4j.api.IRoleService;
import com.yuanheng100.ems4j.mapper.Ems4jEmployeeMapper;
import com.yuanheng100.ems4j.mapper.Ems4jRoleMapper;
import com.yuanheng100.ems4j.model.Ems4jEmployee;
import com.yuanheng100.ems4j.model.Ems4jRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by jlqian on 2017/1/11.
 */
@Service
public class RoleServiceImpl implements IRoleService
{
    private static Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Autowired
    private Ems4jRoleMapper ems4jRoleMapper;
    @Autowired
    private Ems4jEmployeeMapper ems4jEmployeeMapper;

    @Override
    public Ems4jRole getRoleById(Integer roleid)
    {
        return ems4jRoleMapper.selectByPrimaryKey(roleid);
    }

    @Override
    public int addRole(Ems4jRole role)
    {
        role.setCreatetime(new Date());
        logger.info("新增角色：" + JSON.toJSONString(role));
        return ems4jRoleMapper.insert(role);
    }

    @Override
    public boolean updateRole(Ems4jRole role)
    {
        logger.info("修改角色：" + JSON.toJSONString(role));
        return ems4jRoleMapper.updateByPrimaryKey(role) == 1;
    }

    @Override
    public int addRoleToEmployee(int roleid, int userid)
    {
        //检查Role和User是否存在
        if (ems4jRoleMapper.selectByPrimaryKey(roleid) != null && ems4jEmployeeMapper.selectByPrimaryKey(userid) != null)
        {
            logger.info("对员工：" + userid + "增加角色：" + roleid);
            return ems4jRoleMapper.addRoleToEmployee(roleid, userid);
        }
        return 0;
    }

    @Override
    public int removeRoleFromEmployee(int roleid, int userid)
    {
        logger.info("从员工：" + userid + "移除角色：" + roleid);
        return ems4jRoleMapper.removeRoleFromEmployee(roleid, userid);
    }

    @Override
    public List<Ems4jRole> getEmployeeRole(int userid)
    {
        return ems4jRoleMapper.selectByUserid(userid);
    }

    @Override
    public List<Ems4jEmployee> getEmployeeByRole(int roleId)
    {
        return ems4jRoleMapper.selectEmployeeByRoleid(roleId);
    }

    @Override
    public List<Ems4jRole> getRoleList(int appId)
    {
        return ems4jRoleMapper.selectRoleListByAppId(appId);
    }

    @Override
    public List<Ems4jRole> getAllRoles()
    {
        return ems4jRoleMapper.selectAll();
    }
}
